package com.agh.portal.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.agh.portal.domain.AghGroup;
import com.agh.portal.domain.GroupEvent;
import com.agh.portal.domain.Student;
import com.agh.portal.service.SecurityUtils;

@RequestMapping("/groupevents")
@Controller
@RooWebScaffold(path = "groupevents", formBackingObject = GroupEvent.class)
@RooWebFinder
public class GroupEventController {
	
	@Autowired
	SecurityUtils secUtils;
	
    @RequestMapping(params = {"form", "groupId"}, produces = "text/html")
    public String createForm(Model uiModel, @RequestParam(value = "groupId", required = false) Long groupId) {
        uiModel.addAttribute("aghGroup", AghGroup.findAghGroup(groupId));
        populateEditForm(uiModel, new GroupEvent());
        return "groupevents/create";
    }
    
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid GroupEvent groupEvent, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        
    	AghGroup aghGroup = groupEvent.getAghGroup();
    	Student student = groupEvent.getStudent();
		if (aghGroup == null || student == null || !aghGroup.getStudents().contains(student)) {
			bindingResult.rejectValue("actionError", "action_not_permited");
		}
    	
    	if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, groupEvent);
            return "groupevents/create";
        }
        uiModel.asMap().clear();
        groupEvent.setEventDate(new Date());
        groupEvent.persist();
        return "redirect:/groupevents/" + encodeUrlPathSegment(groupEvent.getId().toString(), httpServletRequest);
    }
	
    void populateEditForm(Model uiModel, GroupEvent groupEvent) {
        uiModel.addAttribute("groupEvent", groupEvent);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("student", secUtils.getLoggedStudent());
    }
}
